// pages/register/register.js
const request = require('../../utils/request');
const Toast = require('../../utils/toast');

Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    nickname: ''
  },

  inputUsername(e) {
    this.setData({ username: e.detail.value });
  },

  inputPassword(e) {
    this.setData({ password: e.detail.value });
  },

  inputConfirmPassword(e) {
    this.setData({ confirmPassword: e.detail.value });
  },

  inputPhone(e) {
    this.setData({ phone: e.detail.value });
  },

  inputNickname(e) {
    this.setData({ nickname: e.detail.value });
  },

  async doRegister() {
    const { username, password, confirmPassword, phone, nickname } = this.data;

    // 验证
    if (!username || !password || !phone) {
      Toast.error('请填写完整信息');
      return;
    }

    if (!/^[a-zA-Z0-9_]{4,20}$/.test(username)) {
      Toast.error('用户名应为4-20位字母、数字或下划线');
      return;
    }

    if (password.length < 6) {
      Toast.error('密码长度不能少于6位');
      return;
    }

    if (password !== confirmPassword) {
      Toast.error('两次输入的密码不一致');
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      Toast.error('请输入正确的手机号');
      return;
    }

    Toast.loading('注册中...');

    try {
      const res = await request.post('/user-auth/register', {
        username,
        password,
        phone,
        nickname: nickname || username
      });

      Toast.hideLoading();

      if (res.success) {
        Toast.success('注册成功');
        
        // 保存token和用户信息
        wx.setStorageSync('token', res.data.token);
        wx.setStorageSync('userInfo', res.data.user);

        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1000);
      } else {
        Toast.error(res.message || '注册失败');
      }
    } catch (error) {
      Toast.hideLoading();
      console.error('注册失败:', error);
      Toast.error('网络错误');
    }
  }
});

